﻿using ChuanYe.WorkLogManagement.EF.SqlServer;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace ChuanYe.WorkLogManagement.BLL
{
    public class PositionBLL
    {
        #region 构造单例
        private PositionBLL() { }
        private static PositionBLL _instance;
        public static PositionBLL Instance
        {
            get
            {
                return _instance ?? (_instance = new PositionBLL());
            }
        }
        #endregion

        public int AddOrUpdate(PositionInfo info)
        {
            int positionID = 0;
            using (WorkLogContext context = new WorkLogContext())
            {
                if (info.PositionID > 0)
                {
                    var exist = context.PositionInfo.Where(p => p.PositionID == info.PositionID).FirstOrDefault();
                    if (exist == null)
                    {
                        return -1;
                    }
                    exist.PositionName = info.PositionName;
                    exist.Sort = info.Sort;
                    context.PositionInfo.Add(exist);
                    context.Entry<PositionInfo>(exist).State = EntityState.Modified;
                    context.SaveChanges();
                    positionID = info.PositionID;
                }
                else
                {
                    context.PositionInfo.Add(info);
                    context.Entry<PositionInfo>(info).State = EntityState.Added;
                    context.SaveChanges();
                    positionID = info.PositionID;
                }
               
            }
            return positionID;
        }

        public int Remove(int positionID)
        {
            using (WorkLogContext context = new WorkLogContext())
            {
                var exist = context.PositionInfo.Where(p => p.PositionID == positionID).FirstOrDefault();
                if (exist == null)
                {
                    return 0;
                }
                context.PositionInfo.Add(exist);
                context.Entry<PositionInfo>(exist).State = EntityState.Deleted;
                context.SaveChanges();
                return 1;
            }
        }

        public List<PositionInfo> Get()
        {
            using (WorkLogContext context = new WorkLogContext())
            {
                return context.PositionInfo.OrderBy(o => o.PositionID).ToList();
            }
        }
    }
}
